const path = require('path');
const fs = require('fs-extra');
const express = require('express');
const multer = require('multer');
const { getImageManifest } = require('./manifest');
const { getFileHash } = require('./handy');

const router = express.Router();

router.post('/clean-cache', (req, res) => {
    console.log('clean-cache');
    const uuid = req.body.uuid;
    console.log('uuid: ' + uuid);
    const userUploadDir = path.join(global.__rootDir, 'uploads', uuid);
    console.log('clean upload folder: ' + userUploadDir);
    fs.removeSync(userUploadDir);
    res.json({ code: 200, message: '删除成功' });
});

const upload = multer({ storage: multer.memoryStorage() });

router.post('/get-file', upload.none(), async (req, res) => {
    console.log('get file');
    const uuid = req.body.uuid;
    if (!uuid) {
        res.json({ code: 400, message: 'uuid不能为空' });
        return;
    }
    const fileHash = req.body.fileHash;
    if (!fileHash) {
        res.json({ code: 400, message: 'fileHash不能为空' });
        return;
    }
    const fileName = req.body.fileName;
    if (!fileName) {
        res.json({ code: 400, message: 'fileName不能为空' });
        return;
    }
    const zipFileHash = req.body.zipFileHash;
    if (!zipFileHash) {
        res.json({ code: 400, message: 'zipFileHash不能为空' });
        return;
    }
    console.log('下载PDF文件：' + fileName);
    const uploadRootDir = path.join(global.__rootDir, 'uploads', uuid);
    const userUploadDir = path.join(uploadRootDir, zipFileHash);
    const filePath = path.join(userUploadDir, fileName);
    const pdfFileHash = await getFileHash(filePath);
    console.log('获取文件: ' + filePath);
    const imageManifest = getImageManifest({ zipFileHash, pdfFileHash, uuid });
    if (
        Array.isArray(imageManifest.imageList) &&
        imageManifest.imageList.length
    ) {
        res.json(imageManifest);
        return;
    }
    console.log('下载文件：' + filePath);
    res.download(filePath, (err) => {
        if (err) {
            console.log(err);
            res.json({ code: 500, message: '文件下载失败' });
        }
    });
});

module.exports = router;
